//封装购物车模块
import { defineStore } from "pinia";
import { ref, computed } from "vue";
//引入购物车API
import {
  addToCart,
  getNewCartList,
  delShoppingCart,
  MergeShoppingCart,
} from "@/apis/cart";
//引入用户信息仓库
import { useUserStore } from "./userStore";
export const useCartStore = defineStore(
  "cart",
  () => {
    //应用用户仓库
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);
    // const isLogin = userStore.userInfo.token;
    console.log("isLogin:", isLogin);
    //定义state
    const cartList = ref([]); //购物车列表

    //添加购物车操作
    const addCart = async (detailGoodsList) => {
      //解构参数
      const { skuId, count } = detailGoodsList;
      // console.log(skuId, count);

      //判断是否有token;有token调接口  无token走本地购物车
      if (isLogin.value) {
        //登录之后加入购物车逻辑
        await addToCart({ skuId, count });
        //获取最新的购物车列表
        updateCart();
      } else {
        //已添加count++ 未添加:push到cartList数组中
        let item = cartList.value.find((item) => {
          return detailGoodsList.skuId === item.skuId;
        });
        if (item) {
          item.count++;
        } else {
          cartList.value.push(detailGoodsList);
        }
      }
    };
    //接口获取最新购物车列表
    const updateCart = async () => {
      let res = await getNewCartList();
      cartList.value = res.result;
    };

    //删除购物车 思路：
    //1.找到需要删除的skuId - splice(skuId,1)
    //2.使用数组的过滤方法filter()
    const delCart = async (skuId) => {
      if (isLogin.value) {
        await delShoppingCart([skuId]);
        //重新调取购物车最新接口
        updateCart();
      } else {
        //   const index = cartList.value.findIndex((item) => {
        //     return skuId === item.skuId;
        //   });
        //   cartList.value.splice(index, 1);
        // 使用 filter 方法过滤掉不需要的元素
        cartList.value = cartList.value.filter((item) => item.skuId !== skuId);
      }
    };

    //清除购物车数据
    const clearCart = () => {
      cartList.value = [];
    };

    //单选功能
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId);
      item.selected = selected;
    };
    // 全选功能
    const allCheck = (selected) => {
      // 把cartList中的每一项的selected都设置为当前的全选框状态
      cartList.value.forEach((item) => (item.selected = selected));
    };

    //合并购物车 map返回一个新的数组
    const MergeCart = async () => {
      await MergeShoppingCart(
        cartList.value.map((item) => {
          return {
            skuId: item.skuId,
            selected: item.selected,
            count: item.count,
          };
        })
      );
      //获取最新列表
      updateCart();
    };

    // 计算属性
    //1.计算总数量
    const allCount = computed(() => {
      return cartList.value.reduce((prev, current) => {
        return prev + current.count;
      }, 0);
    });
    //2.计算总价格
    const allPrice = computed(() => {
      return cartList.value.reduce((prev, current) => {
        return prev + current.count * current.price;
      }, 0);
    });
    //3.是否全选按钮
    const isAllCheck = computed(() => {
      return cartList.value.every((item) => item.selected);
    });

    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      isAllCheck,
      allCheck,
      updateCart,
      clearCart,
      MergeCart,
    };
  },
  {
    persist: true,
  }
);
